package com.niit.chapter2;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 实现登录功能的逻辑
 * @author yaojianfeng
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {


    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        ServletContext context = req.getServletContext();
        //模拟从数据库获取账户密码
        String dbUsername =  context.getInitParameter("username");
        String dbPassword =  context.getInitParameter("password");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        //首先匹配用户名
        if (dbUsername.equals(username)) {
            //匹配密码
            if (dbPassword.equals(password)) {
                //匹配成功跳转到首页
                req.getRequestDispatcher("/home").forward(req,resp);
            } else {
                //匹配失败显示失败页面,提供返回登录页按钮
                resp.sendRedirect(req.getContextPath()+"/LoginFail.html");
            }
        } else {
            //账号匹配失败 则显示注册页面
            resp.sendRedirect(req.getContextPath()+"/LoginFail.html");
        }
    }
}